package com.exam.demo.mapreduce;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * @author SongYueSheng
 * @date 2024/6/7 14:28
 */
public class FixTemperatureMapper extends Mapper<LongWritable, Text, Text, Text> {
    private Text word = new Text();

    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        if (line.startsWith("STN---")) {
            return; // 跳过表头
        }

        String[] fields = line.split("\\s+");
        if (fields.length > 3) {
            String tempStr = fields[3];
            try {
                double tempFahrenheit = Float.parseFloat(tempStr);
                double tempCelsius = (tempFahrenheit - 32) * 5 / 9;
                if (tempCelsius >= 25 && tempCelsius <= 35) {
                    context.write(new Text(fields[0] + "-" + fields[1] + "-" + fields[2]), new Text(String.format("%.2f", tempCelsius)));
                }
            } catch (NumberFormatException e) {
                // 忽略格式错误
            }
        }
    }
}